<?php

namespace App\Admin\Controllers;

use App\Area;
use App\Http\Controllers\Controller;
use App\Product;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class AreasController extends Controller
{
    use HasResourceActions;
    public function __construct()
    {
        header('Access-Control-Allow-Origin: *');
    }

    public $fields = ['rs', 'it', 'et', 'rh', 'cp', '5k', 'dv', 'da', 'dw', 'dh', 'ds', 'dc', 'df'];
    public $fieldNames = ['信号强度','内部温度','外部温度','湿度','风机转速','继电器状态','交流电压','交流电流','有功功率','有功总电能','功率因素','二氧化碳排量','频率',];

    // 地图坐标
    public function positions()
    {
        $data = Product::All()->map(function ($product) {
            $record = $product->records()->latest()->first();
            return [
                'name' => $product->name,
                'lat' => $product->lat,
                'lng' => $product->lng,
                'it' => $record->it,
                'et' => $record->et,
                'rh' => $record->rh
            ];
        });
        // dd($data);
        return $data;
    }

    public function showType($type)
    {
        if (!in_array($type, $this->fields) && $type != 'te') {
            abort(403, '类型错误');
        }
        return view('index.index', compact('type'));
    }

    public function map()
    {
        return view('index.map');
    }

    // 设备目录树
    public function tree()
    {
        $area = Area::with('products')->get()->map(function ($area) {
            return [
                'title' => $area->name,
                'type' => 'folder',
                'products' => $area->products->map(function ($product) {
                    return ['type' => 'item', 'title' => $product->name];
                }),
            ];
        });
        return $area;
    }

    // 设备目录树数据
    public function treeData(Request $request)
    {
        $product = Product::where('name', $request->title)->first();
        if (is_null($product)) {
            abort(403, "名称错误，找不到设备");
        }
        $times = collect();
        $data = [];
        $type = $request->type == 'te' ? ['it', 'et'] : [$request->type];
        $fields = array_intersect($this->fields, $type);
        $keys = array_keys($fields);
        $fieldNames = array_values(array_only($this->fieldNames, $keys));
        $fields = array_values($fields);
        $product->records->each(function ($record) use ($fields, $fieldNames, &$data, &$times) {
            $times->push($record->created_at->toDateTimeString());
            foreach ($record->only($fields) as $field => $value) {
                $key = array_search($field, $fields);
                $data[$key]['name'] = $fieldNames[$key];
                // $data[$key]['alias'] = $field;
                $data[$key]['type'] = 'line';
                $data[$key]['symbol'] = 'none';
                $data[$key]['smooth'] = true;
                $data[$key]['data'][] = $value;
            }
        });

        return ['times' => $times, 'data' => $data, 'titles' => $fieldNames];
    }

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('Index')
            ->description('description')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('Edit')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Create')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Area);

        $grid->id('Id');
        $grid->name('Name');
        $grid->parent_id('Parent id');
        $grid->status('Status');
        $grid->sort('Sort');
        $grid->created_at('Created at');
        $grid->updated_at('Updated at');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Area::findOrFail($id));

        $show->id('Id');
        $show->name('Name');
        $show->parent_id('Parent id');
        $show->status('Status');
        $show->sort('Sort');
        $show->created_at('Created at');
        $show->updated_at('Updated at');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Area);

        $form->text('name', 'Name');
        $form->number('parent_id', 'Parent id');
        $form->number('status', 'Status')->default(1);
        $form->number('sort', 'Sort');

        return $form;
    }
}
